package com.example.dishchickenimageloader;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCache {
   private static final String absolutePath = MyApplication.getContext().getCacheDir().getAbsolutePath();

    public static void save(String url, Bitmap bitmap){
        try {

            File bitmapFile = new File(absolutePath + "/" + turnUrlToFileName(url));
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(bitmapFile));
            new Thread(() -> {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                try {
                    bos.flush();
                    bos.close();
                    Log.e("FileCache：save", url + "压缩保存成功");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }


    public static Bitmap get(String url){
        try {
            String s = absolutePath + "/" + turnUrlToFileName(url);
            FileInputStream fis = new FileInputStream(s);
            Bitmap bitmap = BitmapFactory.decodeStream(fis);
            if(bitmap != null){
                return bitmap;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void remove(String url){
        File file = new File(absolutePath + "/" + turnUrlToFileName(url));
        if(file.isFile()){
            boolean delete = file.delete();
            if(!delete){
                Log.e("FileCache", "remove: 删除失败");
            }else {
                Log.e("FileCache：remove",  url + "已从文件缓存移除，加入内存缓存");
            }
        }
    }


    private static String turnUrlToFileName(String url){
        return url.replace("/", "");
    }

}
